/**
 * 
 */
package leetCode;

import java.util.ArrayList;

/**
 * @author zhong
 *
 */
public class AsteroidCollision {
	public int[] asteroidCollision(int[] asteroids) {
		if (asteroids == null || asteroids.length < 2) {
			return asteroids;
		}
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < asteroids.length; i++) {
			boolean disappear = false;
			while (!list.isEmpty() && oppoDir(list.get(list.size() - 1), asteroids[i])) {
				int size1 = Math.abs(list.get(list.size() - 1));
				int size2 = Math.abs(asteroids[i]);
				if (size1 == size2) {
					list.remove(list.size() - 1);
					disappear = true;
					break;
				} else if (size1 < size2) {
					list.remove(list.size() - 1);
				} else {
					disappear = true;
					break;
				}
			}
			if (!disappear) {
				list.add(asteroids[i]);
			}
		}
		int[] res = new int[list.size()];
		for (int i = 0; i < res.length; i++) {
			res[i] = list.get(i);
		}
		return res;
	}

	private boolean oppoDir(Integer integer, int i) {
		return (integer > 0 && i < 0);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] asteroids = { -2, -2, -2, 1 };
		int[] res = new AsteroidCollision().asteroidCollision(asteroids);
		for (int i = 0; i < res.length; i++) {
			System.out.println(res[i]);
		}
	}

}
